<template>
  <div class="login-page">
    <ElForm
      ref="loginFormRef"
      class="login-form"
      :rules="loginRules"
      :model="loginForm"
    >
      <div class="admin-logo">
        <img class="logo" src="../../assets/vue.svg" alt="logo" size-80px />
        <h1 class="name">Vue3 Admin</h1>
      </div>
      <ElFormItem prop="username">
        <ElInput placeholder="请输入用户名" v-model="loginForm.username">
          <template #prepend>
            <span class="svg-container">
              <SvgIcon icon-name="ant-design:user-add-outlined"></SvgIcon>
            </span>
          </template>
        </ElInput>
      </ElFormItem>
      <ElFormItem prop="password">
        <ElInput
          v-model="loginForm.password"
          type="password"
          autocomplete="on"
          show-password
          placeholder="请输入密码"
        ></ElInput>
      </ElFormItem>
      <!-- 登录按钮 -->
      <ElButton @click="handleLogin" type="primary" w-full mb-30px
        >登录</ElButton
      >
    </ElForm>
  </div>
</template>

<script lang="ts" setup>
import { useRouteQuery } from "@/hooks/useRouteQuery";
import { useUserStore } from "@/stores/login";
import { FormInstance } from "element-plus";

const loginState = reactive({
  loginForm: {
    username: "",
    password: ""
  },
  loginRules: {
    username: [
      {
        required: true,
        trigger: "blur",
        message: "请输入用户名"
      }
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: "请输入用户密码"
      }
    ]
  }
});

const { loginForm, loginRules } = loginState;
const router = useRouter();
const { redirect, otherQuery } = useRouteQuery();

// 实际上ref和model的值不能一致， 不然会导致输入框无法输入
const loginFormInstance = useTemplateRef<FormInstance>("loginFormRef"); // vue3.5不用关心ref重名的问题

const useStore = useUserStore();
const handleLogin = async () => {
  loginFormInstance.value?.validate(async (valid) => {
    if (valid) {
      await useStore.login(loginForm);

      // router.push({ path: "/" });
      // 这里需要解析出一个重定向的路径和其他的查询的参数
      // 这里通过一个钩子实现
      router.push({
        path: redirect.value || "/",
        query: otherQuery.value
      });
    }
  });
};
</script>

<style lang="scss" scoped>
.login-page {
  @apply min-h-screen w-full;
  .login-form {
    @apply w-500px mx-auto py-50px;
    .admin-logo {
      @apply flex items-center justify-center mx-20px my-10px;
    }
  }
}
</style>
